package org.nbict.iot.trident.mogo.mapper.impl;

import org.apache.storm.mongodb.common.QueryFilterCreator;
import org.apache.storm.tuple.ITuple;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.nbict.iot.trident.mogo.mapper.MongoMapper;

/**
 * 简单更新
 * Created by songseven on 18/6/25.
 */
public class SimpleMongoUpdateMapper implements MongoMapper {

    private String[] fields;
    private QueryFilterCreator filterCreator;

    public SimpleMongoUpdateMapper() {
    }

    @Override
    public Document toDocument(ITuple tuple) {
        Document document = new Document();
        String[] var3 = this.fields;
        int var4 = var3.length;

//        try {
//            System.out.println(tuple);
//        } catch (RuntimeException e) {
//            throw new RuntimeException(e);
//        }

        for(int var5 = 0; var5 < var4; ++var5) {
            String field = var3[var5];
            if (tuple.getValueByField(field) != null) {
                document.append(field, tuple.getValueByField(field));
            }
        }

        return new Document("$set", document);
    }

    /**
     * 过滤条件
     * @param tuple
     * @return
     */
    @Override
    public Bson filter(ITuple tuple) {
        return filterCreator != null? filterCreator.createFilter(tuple) : null;
    }

    public SimpleMongoUpdateMapper withFields(String... fields) {
        this.fields = fields;
        return this;
    }

    public SimpleMongoUpdateMapper withFilter(QueryFilterCreator filterCreator) {
        this.filterCreator = filterCreator;
        return this;
    }


}
